package com.ltu.timkor6.gamesite.users.server;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import java.util.ArrayList;
import java.util.List;
import com.ltu.timkor6.gamesite.server.GameSiteServiceImpl;
import com.ltu.timkor6.gamesite.shared.DBUsers;
import com.ltu.timkor6.gamesite.shared.UserInfo;
import com.ltu.timkor6.gamesite.users.client.RegisterStatus;
import com.ltu.timkor6.gamesite.users.client.SignInStatus;
import com.ltu.timkor6.gamesite.users.client.UsersService;

@SuppressWarnings("serial")
public class UsersServiceImpl extends GameSiteServiceImpl implements UsersService
{
	public UsersServiceImpl()
	{
	}
	
	// Sign in
	public SignInStatus signIn(String[] credentials)
	{		
		userInfo = dbUserInfo(credentials[0]);
		
		SignInStatus status = SignInStatus.UNKNOWN;
		
		if(userInfo == null)
		{
			status = SignInStatus.NO_USER;
		}
		else if(userInfo.getPassword() == null)
		{
			status = SignInStatus.NO_PASS;
		}
		else if(credentials[0].compareTo(userInfo.getUserName()) == 0 && credentials[1].compareTo(userInfo.getPassword()) == 0)
		{
			this.setUserInSession(userInfo);
			status = SignInStatus.SUCCESS;
		}
		else
		{
			status = SignInStatus.NO_MATCH;
		}
		
		return status;
	}
	
	// Sign out
	public SignInStatus signOut()
	{
		this.invalidateSession();
		return SignInStatus.SUCCESS;
	}
	
	// Get user
	public UserInfo getUserInfo()
	{
		return this.getUserFromSession();
	}
	
	// Add user
	public RegisterStatus register(UserInfo userInfo)
	{
		UserInfo found = dbUserInfo(userInfo.getUserName());
		if(found == null)
		{
			PersistenceManager pm = getPersistenceManager();
			try
			{
				pm.makePersistent(new DBUsers(userInfo.getUserName(), userInfo.getPassword()));
			}
			finally
			{
				pm.close();
			}
			
			return RegisterStatus.SUCCESS;
		}
		else
		{
			return RegisterStatus.USERNAME_TAKEN;
		}
	}
	
	// Fetch user from database
	@SuppressWarnings("unchecked")
	private UserInfo dbUserInfo(String username)
	{
		PersistenceManager pm = getPersistenceManager();
		
		List<UserInfo> list = new ArrayList<UserInfo>();
		try
		{
			Query q = pm.newQuery(DBUsers.class, "userName == u");
			q.declareParameters("String u");
			List<DBUsers> db = (List<DBUsers>) q.execute(username);
			for(DBUsers info : db)
			{
				list.add(new UserInfo(info.getUserName(), info.getPassword(), info.isAdmin()));
			}
		}
		finally
		{
			pm.close();
		}
		
		if(list.isEmpty())
		{
			return null;
		}
		else
		{
			return list.get(0);
		}
	}
}
